<?php

class Model {

    /**
     * @var Database
     *
     */
    public $db;

    function __construct() {
        $this->db = new Database(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);
    }
    
    
    public function getData(){
        return array();
    }


    protected function updateCurrentStock($dummy = true){
        //dummy, because update stock at load price
        if ($dummy){
            //return;
        }


        $max = $this->db->select("SELECT MAX(id) FROM stock");
        //var_dump($max);
        if(is_array($max) && count($max)){
            $res = array_values($max[0]);
            $this->updateStock($res[0]);
        }

    }



    protected  function updateStock($id){
        //if stock is settled, this settle can not be updated
        $sth = $this->db->prepare("SELECT * FROM stock WHERE id = :id");
        //echo "3";
        $sth->execute(array(':id' => $id));
        $stock = $sth->fetch();
        if ($sth->rowCount() > 0 && $stock['status'] == Database::$JA){
            //echo "Notice, this stock can not be updated!!";
            return;
        }

        //clear current stock articles
        $where = 'stock_id = '.$id;
        $this->db->delete('`stock_article`', $where);
        //echo "remove:".$id;
        //return;
        //echo "clear stocks";
        //return;
        //echo "ni da ye";

        //load purchase article
        $sql = "SELECT * FROM `purchase` WHERE `lock`='".Database::$Nein."' AND `status`='".Database::$In."'";

        $sth = $this->db->prepare($sql);
        $sth->execute();
        $purchaseList = $sth->fetchAll();
        $idList = array();
        foreach($purchaseList AS $purchase){
            $idList[] = $purchase['id'];
        }

        //var_dump($idList);

        $sql = "SELECT * FROM article LEFT JOIN purchase_article ON article.id = purchase_article.article_id  WHERE purchase_id IN (".implode(' ,', $idList).")";

        $sth = $this->db->prepare($sql);
        //echo $sql;
        //echo "3";
        $sth->execute();
        $articlePurchaseList = $sth->fetchAll();
        //var_dump($articlePurchaseList);



        // load order article

        $sql = "SELECT * FROM `order` WHERE `lock`='".Database::$Nein."' AND `order_status`='".Database::$AUS."'";
        //echo $sql;

        $sth = $this->db->prepare($sql);
        $sth->execute();
        $orderList = $sth->fetchAll();
        $idList = array();
        foreach($orderList AS $order){
            $idList[] = $order['id'];
        }

        //var_dump($idList);

        $sql = "SELECT * FROM `article` LEFT JOIN `order_article` ON article.id = order_article.article_id WHERE order_id IN (".implode(' ,', $idList).")";

        $sth = $this->db->prepare($sql);
        //echo $sql;
        //echo "3";
        $sth->execute();
        $articleOrderList = $sth->fetchAll();
        //var_dump($articleOrderList);
        //$articleOrderList =array();

        //init stock article list
        $cols = array('count', 'total_price_e', 'article_id');
        $stockArticleList = array();
        //$sourceList  = array_merge($articlePurchaseList, $articleOrderList);
        $sourceList = $articlePurchaseList;
        if (is_array($sourceList) && count($sourceList)){
            foreach($sourceList AS $item){
                if(isset($stockArticleList[$item['article_id']])){
                    foreach($cols AS $col){
                        if ($col != 'article_id')
                         $stockArticleList[$item['article_id']][$col] += $item[$col];
                        else
                         $stockArticleList[$item['article_id']][$col] = $item[$col];
                    }

                }else{
                   foreach($cols AS $col){
                       $stockArticleList[$item['article_id']][$col] = $item[$col];
                   }
                }
                $stockArticleList[$item['article_id']]['stock_id'] = $id;
            }

        }
        //var_dump($stockArticleList);
        $sourceList = $articleOrderList;
        //$sourceList = $articlePurchaseList;

        //@TODO fix stock status

        if (is_array($sourceList) && count($sourceList)){
            foreach($sourceList AS $item){
                if(isset($stockArticleList[$item['article_id']])){
                    foreach($cols AS $col){
                        if ($col != 'article_id'){

                            if($col == 'total_price_e'){
                                $stockArticleList[$item['article_id']][$col] -= ($item['recommend_price'] * $item['count']);

                            }else{
                                $stockArticleList[$item['article_id']][$col] -= $item[$col];
                            }

                        }

                        else
                            $stockArticleList[$item['article_id']][$col] = $item[$col];
                    }

                }else{
                    foreach($cols AS $col){
                        if($col == 'total_price_e'){
                            $stockArticleList[$item['article_id']][$col] = (-1) * $item['recommend_price'] * $item['count'];
                        }
                        else if ($col == 'count'){
                            $stockArticleList[$item['article_id']][$col] = (-1) * $item[$col];
                        }
                        else
                            $stockArticleList[$item['article_id']][$col] = $item[$col];
                    }
                }
                $stockArticleList[$item['article_id']]['stock_id'] = $id;
                /*if ($stockArticleList[$item['article_id']]['total_price_e'] <= 0 || $stockArticleList[$item['article_id']]['count'] <= 0){
                    unset($stockArticleList[$item['article_id']]);
                }*/
            }

        }

        //var_dump($stockArticleList);

        foreach($stockArticleList AS $stockArticle){
            $price = 0;
            $totalPrice = 0;

            if (intval($stockArticle['count'])>0){
                $price = $stockArticle['total_price_e'] / $stockArticle['count'];
                $totalPrice = $stockArticle['total_price_e'];
            }

            $this->db->insert('`stock_article`', array('count'=>$stockArticle['count'], 'total_price_e'=>$totalPrice, 'article_id'=>$stockArticle['article_id'], 'stock_id'=>$id, 'price_e'=>$price));


        }






        //﻿SELECT * FROM `article` LEFT JOIN `purchase_article` ON `article`.`id` = `purchase_article`.`article_id` WHERE purchase_article.status = In AND purchase_article.lock = Nein

        /*$sql = "SELECT * FROM article LEFT JOIN order_article ON article.id = order_article.article_id WHERE ";

        $sth = $this->db->prepare($sql);

        //echo "3";
        $sth->execute(array(':id' => $data['orderId']));


        $einkauflist = $sth->fetchAll();*/




    }

}